<script lang="ts" setup>
import { onMounted, ref, toRefs, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { randomString } from '@/utils/string'

const props = defineProps({
  list: {
    type: Array,
    default: () => {
      return []
    },
  },
  isFooter: {
    type: Boolean,
    default: false,
  },
  isFile: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['change'])

const { list } = toRefs(props)
const tableData: any = ref([])

onMounted(() => {
  tableData.value = readTree(JSON.parse(JSON.stringify(list.value)))
})

watch(list, (newValue) => {
  tableData.value = readTree(JSON.parse(JSON.stringify(newValue)))
})

function handleAdd() {
  const item = getItem()
  tableData.value.push(item)
  handleChange()
}

// function handleAddItem(row: any) {
//   const item = getItem()
//   if (!row.children) {
//     row.children = []
//   }
//   row.children.push(item)
//   handleChange()
// }

function getItem() {
  return {
    id: randomString(16),
    key: '',
    value: '',
    description: '',
    type: 'text',
    list: [],
  }
}

function handleDelete(row: any) {
  tableData.value = remoteChild(tableData.value, row.id)
  handleChange()
}

function remoteChild(data: any, id: string) {
  return data
    .filter((item: any) => item.id !== id)
    .map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = remoteChild(item.children, id)
      }
      return item
    })
}

function handleDeleteAll(_index: any) {
  tableData.value = []
  handleChange()
}

function handleChange() {
  emit('change', tableData.value)
}

// id为null时设置默认id
function readTree(treeNodes: any, index: number | string = -1) {
  if (!treeNodes || !treeNodes.length)
    return []

  for (let idx = 0, len = treeNodes.length; idx < len; idx++) {
    const childs = treeNodes[idx].children
    const autoIdx = idx + 1
    // 为null时设置id
    if (treeNodes[idx].id === null) {
      if (index === -1) {
        treeNodes[idx].id = `${autoIdx}`
      }
      else {
        treeNodes[idx].id = `${index}_${autoIdx}`
      }
    }
    // 子项遍历
    if (childs && childs.length > 0) {
      if (index === -1) {
        readTree(childs, `${autoIdx}`)
      }
      else {
        readTree(childs, `${index}_${autoIdx}`)
      }
    }
  }
  return treeNodes
}

const uploadRef: any = ref(null)
let currentRow: any = {}
function handleUpload(row: any) {
  currentRow = row
  uploadRef.value.$el.querySelector('input').click()
}

function handleRemove(row: any, ele: any) {
  row.list = row.list.filter((item: any) => item.uid !== ele.uid)
}

function beforeUpload(file: any) {
  // const typeArr: any = []
  // const type = file.name.substring(file.name.lastIndexOf('.'))
  // if (!typeArr.includes(type)) {
  //   ElMessage.warning('请上传符合格式的文件')
  //   return false
  // }
  const size = 1024 * 1024 * 100
  if (file && file.size > size) {
    ElMessage.warning('请上传小于100M的文件')
    return false
  }
  return true
}

// 上传文件
function handleSuccess(_response: any, _uploadFile: UploadFile) {
  currentRow = {}
}

// 上传文件
function httpRequest(file: any) {
  // const formData = new FormData();
  // formData.append('file', file.file);
  tableData.value.map((item: any) => {
    if (item.id === currentRow.id) {
      item.list = [{ uid: file.file.uid, name: file.file.name, size: file.file.size }]
    }

    return item
  })

  return new Promise((resolve) => {
    resolve(true)
  })
}

function handleExceed(files: Array<any>) {
  const file = files[0]
  const fileObj = { file }
  const bool = beforeUpload(file)
  if (bool) {
    httpRequest(fileObj)
  }
}

defineExpose({
  handleAdd,
})
</script>

<template>
  <section class="table-section">
    <el-table
      :data="tableData"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children' }"
      :border="true"
      header-cell-class-name="custom-table-header"
      :style="{ 'height': isFooter ? 'calc(100% - 40px)' : '100%', 'overflow-y': 'auto' }"
    >
      <el-table-column prop="key" label="键" class-name="mix-cell-class">
        <template #default="scope">
          <el-input v-if="isFile" v-model="scope.row.key" placeholder="请输入键" @change="handleChange">
            <template #append>
              <el-select v-model="scope.row.type" style="width: 80px">
                <el-option label="文本" value="text" />
                <el-option label="文件" value="file" />
              </el-select>
            </template>
          </el-input>
          <el-input v-else v-model="scope.row.key" placeholder="请输入键" @change="handleChange" />
        </template>
      </el-table-column>
      <el-table-column prop="value" label="值">
        <template #default="scope">
          <el-input v-if="scope.row.type === 'text'" v-model="scope.row.value" placeholder="请输入值" @change="handleChange" />
          <el-popover v-else :teleported="false">
            <template #reference>
              <div class="mix-dev h-8 w-full flex cursor-pointer items-center border-1 border-[#dcdfe6] rounded bg-white px-2">
                <span v-if="!scope.row.list.length" class="color-[#a8abb2]">请上传文件</span>
                <span v-else>
                  <el-tag
                    v-for="ele in scope.row.list"
                    :key="ele.uid"
                    type="primary"
                    closable
                    effect="light"
                    @close="handleRemove(scope.row, ele)"
                  >
                    {{ ele.name }}
                  </el-tag>
                </span>
              </div>
            </template>

            <el-button
              type="primary"
              text
              :icon="Plus"
              style="width: 100%;"
              @click="handleUpload(scope.row)"
            >
              上传文件
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="scope">
          <el-input v-model="scope.row.description" placeholder="请输入描述" @change="handleChange" />
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作" width="160" align="center">
        <template #default="scope">
          <!--
          <el-button type="primary" link @click="handleAddItem(scope.row)">
            添加
          </el-button>
          -->
          <el-button type="primary" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer v-if="isFooter" class="flex justify-center" style="margin-top: 8px">
      <el-button type="primary" plain @click="handleAdd">
        添加
      </el-button>
      <el-button type="danger" plain @click="handleDeleteAll">
        全部删除
      </el-button>
    </footer>
    <el-upload
      ref="uploadRef"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :http-request="httpRequest"
      :on-exceed="handleExceed"
      style="height: 0; width: 0;"
    />
  </section>
</template>

<style lang="scss" scoped>
.mix-dev:hover {
  border-color: #c0c4cc;
}

.table-section {
  height: 100%;
}

.table-section :deep() .mix-cell-class {
  div {
    display: flex !important;
    align-items: center !important;
  }
}

.table-section :deep() .el-select__wrapper {
  width: 100%;
}

.table-section :deep() .el-popper {
  width: calc(100% - 22px) !important;
  padding: 2px !important;
}
</style>
